package blue.jdbc.internal.core.parser;

import blue.base.core.reflect.JavaBean;
import blue.jdbc.core.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jin Zheng
 * @since 1.0 2021-12-22
 */
public class ServiceConfigParser implements Parser {
	private static Logger logger = LoggerFactory.getLogger(ServiceConfigParser.class);

	private final ServiceConfigCache cache;

	public ServiceConfigParser(ServiceConfigCache cache) {
		this.cache = cache;
	}

	@Override
	public void parse(JavaBean bean) {
		if (cache.exist(bean.getTargetClass())) {
			logger.warn("{} has bean parsed", bean.getTargetClass().getName());
			return;
		}
		// TODO: get setXxxDao() method

		Object object = bean.newInstanceQuietly();
		String name = this.getName(bean);
		DefaultServiceConfig config = new DefaultServiceConfig();
		config.setName(name);
		config.setJavaBean(bean);
		config.setObject(object);
		config.check();
		cache.put(config);
		logger.info("Found @Service [{}]: {}", name, config.getClazz().getName());
	}

	private String getName(JavaBean bean) {
		Service anno = bean.getAnnotation(Service.class);
		String name = anno.name();
		if (!name.isEmpty()) {
			return name;
		}

		String clazzName = bean.getTargetClass().getSimpleName();
		char first = clazzName.charAt(0);
		return Character.toLowerCase(first) + clazzName.substring(1);
	}
}
